/*
 * @Author: 李九阳
 * @Date: 2021-12-13 08:47:15
 * @LastEditors: 李九阳
 * @LastEditTime: 2021-12-14 20:45:19
 */
import Map from "@arcgis/core/Map";
import config from "@arcgis/core/config";
import MapView from "@arcgis/core/views/MapView";
import TileLayer from "@arcgis/core/layers/TileLayer";
import MapImageLayer from "@arcgis/core/layers/MapImageLayer";
import WebMap from "@arcgis/core/WebMap";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Point from "@arcgis/core/geometry/Point";
import Extent from "@arcgis/core/geometry/Extent";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
import Geometry from "@arcgis/core/geometry/Geometry";
import Basemap from "@arcgis/core/Basemap";
import Graphic from "@arcgis/core/Graphic";

import ScaleBar from "@arcgis/core/widgets/ScaleBar";
import Zoom from "@arcgis/core/widgets/Zoom";
import Attribution from "@arcgis/core/widgets/Attribution";
import Search from "@arcgis/core/widgets/Search";
import Home from "@arcgis/core/widgets/Home";
import Compass from "@arcgis/core/widgets/Compass";
import Expand from "@arcgis/core/widgets/Expand";
import BasemapToggle from "@arcgis/core/widgets/BasemapToggle";

import SimpleFillSymbol from "@arcgis/core/symbols/SimpleFillSymbol";
import SimpleLineSymbol from "@arcgis/core/symbols/SimpleLineSymbol";
import PictureMarkerSymbol from "@arcgis/core/symbols/PictureMarkerSymbol";
import SimpleMarkerSymbol from "@arcgis/core/symbols/SimpleMarkerSymbol";

import PopupTemplate from "@arcgis/core/PopupTemplate";
import locator from "@arcgis/core/rest/locator";

// 初始化地图信息
const mapUrl =
  //  "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";
  "http://10.76.130.21/zyzcgis/rest/services/DT/BGDS_ANHUAN_DiTu/MapServer";
let view: any;
let drawLayer: GraphicsLayer;
// let drawSketch!: Sketch;
let map!: Map;
const graphicsLayers: { [type: string]: GraphicsLayer } = {
  draw: new GraphicsLayer(),
};
declare type LayerCommand = string | "draw";

export const initMap = () => {
  // config.assetsPath = '../../../public/assets';
  // // 加载切片
  // const imgLayer = new TileLayer({
  //   url: mapUrl,
  // });
  // const graphicsLayer = new GraphicsLayer();
  // const webMap = new WebMap({
  //   layers: [imgLayer, graphicsLayer],
  // });
  // view = new MapView({
  //   container: "arcGisViewDiv",
  //   map: webMap,
  //   zoom: 4,
  //   center: new Point({
  //     x: 1697.218525103722,
  //     y: 829.1965117263652,
  //     spatialReference: {
  //       wkid: 102100,
  //     },
  //   }),
  //   constraints: {
  //     geometry: new Extent({
  //       // Constrain lateral movement to Lower Manhattan
  //       xmin: 137.53668212890625,
  //       ymin: -22.05352783203125,
  //       xmax: 3064.8862915039062,
  //       ymax: 2817.1704711914062,

  //       // xmin: 942.9299595821321,
  //       // ymin: 522.9892289201503,
  //       // xmax: 2265.079147835322,
  //       // ymax: 2273.053322691234,

  //       // xmin: -1359.089292249431,
  //       // ymin: 381.8031177888645,
  //       // xmax: 4601.455962174411,
  //       // ymax: 3333.853466334006,
  //       spatialReference: {
  //         wkid: 102100,
  //       },
  //     }),
  //     minScale: 250,
  //     maxScale: 64000,
  //     minZoom: 3,
  //     maxZoom: 8,
  //   },
  //   popup: {
  //     collapsed: true,
  //     collapseEnabled: false,
  //     dockEnabled: true,
  //     highlightEnabled: false,
  //     dockOptions: {
  //       position: "top-right",
  //       breakpoint: false,
  //       buttonEnabled: false,
  //     },
  //     visibleElements: {
  //       closeButton: false,
  //       featureNavigation: false,
  //     },
  //   },
  //   // ui: { components: ["zoom", "compass"] }
  // });

  // // view.ui.move(['zoom'], 'bottom-right');
  // view.ui.remove(["zoom"]);
  // view.ui.remove(["attribution"]);
  // // webMap.add(graphicsLayer);
  // // drawLayer = graphicsLayer;

  // const point: any = { //Create a point
  //   type: "point",
  //   longitude: 1667.0447251320984,
  //   latitude: 789.9255098241727
  // };
  // const simpleMarkerSymbol = {
  //   type: "simple-marker",
  //   color: [226, 119, 40],  // Orange
  //   outline: {
  //     color: [255, 255, 255], // White
  //     width: 1
  //   }
  // };
  // const ptGraphic: any = new Graphic({
  //   geometry: point,
  //   symbol: simpleMarkerSymbol
  // });
  // graphicsLayer.add(ptGraphic);

  // map = new Map({
  //   basemap: "streets-navigation-vector",
  //   layers: [graphicsLayers.draw]
  // });

  // drawLayer = graphicsLayers.draw;
  // view = new MapView({
  //   container: "arcGisViewDiv",
  //   map: map,
  //   zoom: 5,
  //   center: [90, 45]
  // });

  config.apiKey = "YOUR_API_KEY";
  const webMap = new Map({
    basemap: "arcgis-topographic", // Basemap layer service
  });

  const mapView = new MapView({
    map: webMap,
    center: [-118.805, 34.027], //Longitude, latitude
    zoom: 13,
    container: "arcGisViewDiv",
  });

  const graphicsLayer = new GraphicsLayer();
  webMap.add(graphicsLayer);
  map = webMap;
  drawLayer = graphicsLayer;
  view = mapView;
};

export const init = () => {
  const basemap = new Basemap({
    baseLayers: [
      new TileLayer({
        url: mapUrl,
        title: "Basemap",
      }),
    ],
    title: "basemap",
    id: "basemap",
  });
  const map = new Map({
    // basemap: "osm",
    basemap: basemap,
  });
  console.log(map);
  console.log(map.layers);
  let tempLayers = null;
  const view = new MapView({
    container: "mapview",
    map: map,
    center: [116.404844, 39.913385],
    zoom: 2,
  });
  // this.view = view;
  const layer = new TileLayer({
    url: mapUrl,
    title: "永久基本农田",
  });
  map.layers.add(layer);
  tempLayers = map.layers;

  view.ui.remove("zoom"); //清除放大缩小按钮
  view.ui.remove("attribution"); //清楚底部powered by ESRI
  console.log(view);
  //   this.map = map;
};

/**
 * 画图工具
 */
const drawSketch = () => {
  // view.when(() => {
  const polygon: any = ["point", "polyline", "polygon"];
  const drawSketch = new Sketch({
    layer: drawLayer,
    view: view,
    creationMode: "update",
    availableCreateTools: polygon,
  });
  view.ui.add(drawSketch, "top-right");
  drawSketch.on("create", (event: any): any => {
    // check if the create event's state has changed to complete indicating
    // the graphic create operation is completed. [0, 249, 63, 1]
    console.log("创建drawSketch");
    console.log(event);
    if (event.tool === "point") {
      const size = "6px";
      event.graphic.symbol = getMarkerSymbol({
        pointStyleType: "picture",
        size,
      });
    }
    if (event.tool === "polyline") {
      event.graphic.symbol = getLineSymbol([24, 144, 255, 0.59]);
    }
    if (event.tool === "polygon") {
      event.graphic.symbol = getSimpleFillSymbol([24, 144, 255]);
    }
    if (event.state === "complete") {
      // remove the graphic from the layer. Sketch adds
      // the completed graphic to the layer by default.
      //   const outputData: DrawDataType = {
      //     uid: event.graphic["uid"],
      //     geometry: event.graphic.geometry,
      //     tool: event.tool,
      //   };
    }
  });
  drawSketch.on("delete", (event): any => {
    // const graphics = event.graphics;
    // for (const graphic of graphics) {
    // }
    console.log("删除drawSketch");
    console.log(event);
  });

  drawSketch.on("update", (event): any => {
    console.log("更新drawSketch");
    console.log(event);
    if (
      (event.state === "start" && event.tool === "transform") ||
      event.state === "active"
    ) {
      //   const graphics = event.graphics;
      //   for (const graphic of graphics) {
      //   }
    }
  });
  // });
};

/**
 * 弹框
 */
const popup = () => {
  view.popup.autoOpenEnabled = false;
  view.on("click", (event: any) => {
    // Get the coordinates of the click on the view
    // around the decimals to 3 decimals
    const lat = Math.round(event.mapPoint.latitude * 1000) / 1000;
    const lon = Math.round(event.mapPoint.longitude * 1000) / 1000;

    view.popup.open({
      // Set the popup's title to the coordinates of the clicked location
      title: "Reverse geocode: [" + lon + ", " + lat + "]",
      location: event.mapPoint, // Set the location of the popup to the clicked location
    });
  });
};
/**
 * 底图切换
 */
const basemapToggle = () => {
  const toggle = new BasemapToggle({
    // 2 - Set properties
    view: view, // view that provides access to the map's 'topo-vector' basemap
    nextBasemap: "hybrid", // allows for toggling to the 'hybrid' basemap
  });
  view.ui.add(toggle, "top-right");
};
/**
 * 初始化小部件
 */
export const widgets = () => {
  drawSketch();
  // basemapToggle();
  // popup();
  // expand();
  // point();
  graphical();
};

// const arcGisControls = (document: any) => {
//   if (document !== null && document !== undefined) {
//     document
//       .getElementById("lineWidth")
//       .addEventListener("calciteSliderChange", updateRenderer);
//     document
//       .getElementById("lineColor")
//       .addEventListener("calciteInputInput", updateRenderer);
//     document
//       .getElementById("density")
//       .addEventListener("calciteSliderChange", updateRenderer);
//     document
//       .getElementById("lineLength")
//       .addEventListener("calciteSliderChange", updateRenderer);
//     document
//       .getElementById("lineSpeed")
//       .addEventListener("calciteSliderChange", updateRenderer);
//     document
//       .getElementById("fadeDuration")
//       .addEventListener("calciteSliderChange", updateRenderer);
//     document
//       .getElementById("effectsEnabled")
//       .addEventListener("calciteCheckboxChange", updateEffect);
//   }

//   function updateEffect(event: any) {
//     let checkbox = event.target.checked ? "bloom(2, 0.5px, 0)" : null;
//     layer.effect = checkbox;
//   }

//   function updateRenderer(event: any) {
//     let propName = event.target.id;
//     let propValue = event.target.value;

//     if (propName && propValue != null) {
//       let tempRenderer = layer.renderer.clone();

//       tempRenderer[propName] = propValue;
//       layer.renderer = tempRenderer;
//     }
//   }
// }

/**
 * 扩大
 */
const expand = () => {
  const cont: any = document.getElementById("configPanel");
  const configurationExpand = new Expand({
    expandIconClass: "esri-icon-settings2",
    expandTooltip: "Show magnifier configuration",
    expanded: true,
    view: view,
    content: cont,
  });

  view.ui.add(configurationExpand, "bottom-left");
  view.when(() => {
    // enable the Magnifier
    view.magnifier.visible = false;
    view.magnifier.factor = 1.7; // magnification factor
    view.magnifier.size = 150; // magnifier image size
    view.magnifier.offset = { x: 75, y: 75 }; // x and y offset values

    // uses the mouse cursor location to position the Magnifier
    view.on("pointer-move", (evt: any) => {
      view.magnifier.position = { x: evt.x, y: evt.y };
    });
    view.watch("focused", (newValue: any) => {
      if (newValue) {
        configurationExpand.expanded = false;
      }
    });

    // setup UI to use the default config values
    setMangifierConfig(view.magnifier);
  });

  function setMangifierConfig(magnifier: any) {
    const toggleSwitch: any = document.getElementById("toggleSwitch");
    const factorInput: any = document.getElementById("factorInput");
    const xoffsetInput: any = document.getElementById("xoffsetInput");
    const yoffsetInput: any = document.getElementById("yoffsetInput");
    const sizeInput: any = document.getElementById("sizeInput");

    // set default input values
    toggleSwitch.switched = magnifier.visible;
    factorInput.value = magnifier.factor;
    xoffsetInput.value = magnifier.offset.x;
    yoffsetInput.value = magnifier.offset.y;
    sizeInput.value = magnifier.size;

    // add calcite event listeners
    toggleSwitch.addEventListener("calciteSwitchChange", (evt: any) => {
      magnifier.visible = evt.target.switched;
    });
    factorInput.addEventListener("calciteInputInput", (evt: any) => {
      magnifier.factor = parseFloat(evt.target.value);
    });
    xoffsetInput.addEventListener("calciteInputInput", (evt: any) => {
      magnifier.offset.x = parseInt(evt.target.value);
    });
    yoffsetInput.addEventListener("calciteInputInput", (evt: any) => {
      magnifier.offset.y = parseInt(evt.target.value);
    });
    sizeInput.addEventListener("calciteInputInput", (evt: any) => {
      magnifier.size = parseInt(evt.target.value);
    });
  }
};
/**
 * 图形层
 * @param type
 */
const getLayer = (type: LayerCommand): GraphicsLayer => {
  switch (type) {
    case "draw":
      return drawLayer; // 默认图层
    default:
      if (graphicsLayers[type] === undefined) {
        graphicsLayers[type] = new GraphicsLayer();
        map.add(graphicsLayers[type]);
      }
      return graphicsLayers[type];
  }
};

/**
 *
 * @param pointParam
 */
const getMarkerSymbol = (
  pointParam: PointParam
): PictureMarkerSymbol | SimpleMarkerSymbol => {
  let type = pointParam.pointStyleType;
  let size = pointParam.size;
  const pictureUrl = pointParam.pictureUrl;
  if (type === "picture" && pictureUrl === undefined) {
    type = "simple";
    size = size === undefined ? "6px" : size;
  }

  if (type === "picture") {
    return new PictureMarkerSymbol({
      url: pictureUrl,
      width: size,
      height: size,
    });
  }
  // [24, 144, 255, 1]
  return new SimpleMarkerSymbol({
    color: pointParam.color,
    outline: {
      color: [255, 255, 255, 1],
      width: 1,
    },
    size,
  });
};

/**
 * @name: 获取线得样式
 * @param {number[]} color 线得颜色 值为rgba参数 eg:[255, 255, 255, 1]
 * @return {SimpleLineSymbol}
 */
const getLineSymbol = (color: number[]): SimpleLineSymbol => {
  // return new SimpleLineSymbol().set('color', color).set('width', 6);
  return new SimpleLineSymbol({
    color,
    width: 6,
    cap: "butt",
  });
};

/**
 * @name: 获取区域填充样式
 * @param {*}
 * @return {SimpleFillSymbol}
 */
const getSimpleFillSymbol = (color: number[]): SimpleFillSymbol => {
  return new SimpleFillSymbol({
    color: [...color, 0.3],
    outline: {
      color: [...color, 0.6],
      width: 1,
    },
  });
};

interface PointParam {
  pointStyleType?: "simple" | "picture";
  size?: string;
  pictureUrl?: string;
  status?: "success" | "error" | "warning";
  color?: Array<number>;
}

interface DrawDataType {
  uid: number;
  geometry: Geometry;
  tool: string;
}

const point = () => {
  const paths = [[1667.0447251320984, 789.9255098241727]];
  // const ptGraphic: any = new Graphic();
  // map.add(ptGraphic);
  const layer: any = getLayer("draw");
  for (let index = 0; index < paths.length; index++) {
    const ptGeometry = new Point({
      x: paths[index][0],
      y: paths[index][1],
    });
    // const ptSymbol = new PictureMarkerSymbol({
    //   url: '../../assets/images/avatar-man.svg',
    //   height: 32,
    //   width: 18,
    // });
    const ptSymbol = new SimpleMarkerSymbol({
      color: [255, 0, 0],
      outline: {
        color: [255, 255, 255, 1],
        width: 1,
      },
      size: 10,
    });
    const ptGraphic: any = new Graphic({
      geometry: ptGeometry,
      symbol: ptSymbol,
    });
    layer.add(ptGraphic);
  }
  // let index = 0;
  // const timePoint = setInterval( () => {
  //   index++;
  //   if (index < paths.length) {
  //     const ptGeometry = new Point({
  //       x: paths[index][0],
  //       y: paths[index][1],
  //       spatialReference: {
  //         wkid: 102100,
  //       },
  //     });
  //     const ptSymbol = new PictureMarkerSymbol({
  //       url: '../../assets/images/avatar-man.svg',
  //       height: 32,
  //       width: 18,
  //     });
  //     ptGraphic.geometry = ptGeometry;
  //     ptGraphic.symbol = ptSymbol;
  //   } else {
  //     clearInterval(timePoint);
  //   }
  // }, 1000);
};

/**
 * 点线面
 */
const graphical = () => {
  const point: any = {
    //Create a point
    type: "point",
    longitude: -118.80657463861,
    latitude: 34.0005930608889,
  };
  const simpleMarkerSymbol = {
    type: "simple-marker",
    color: [226, 119, 40], // Orange
    outline: {
      color: [255, 255, 255], // White
      width: 1,
    },
  };

  const pointGraphic = new Graphic({
    geometry: point,
    symbol: simpleMarkerSymbol,
  });
  drawLayer.add(pointGraphic);

  const polyline: any = {
    type: "polyline",
    paths: [
      [-118.821527826096, 34.0139576938577], //Longitude, latitude
      [-118.814893761649, 34.0080602407843], //Longitude, latitude
      [-118.808878330345, 34.0016642996246], //Longitude, latitude
    ],
  };
  const simpleLineSymbol = {
    type: "simple-line",
    color: [226, 119, 40], // Orange
    width: 2,
  };

  const polylineGraphic = new Graphic({
    geometry: polyline,
    symbol: simpleLineSymbol,
  });
  drawLayer.add(polylineGraphic);

  const polygon: any = {
    type: "polygon",
    rings: [
      [-118.818984489994, 34.0137559967283], //Longitude, latitude
      [-118.806796597377, 34.0215816298725], //Longitude, latitude
      [-118.791432890735, 34.0163883241613], //Longitude, latitude
      [-118.79596686535, 34.008564864635], //Longitude, latitude
      [-118.808558110679, 34.0035027131376], //Longitude, latitude
    ],
  };

  const simpleFillSymbol = {
    type: "simple-fill",
    color: [227, 139, 79, 0.8], // Orange, opacity 80%
    outline: {
      color: [255, 255, 255],
      width: 1,
    },
  };

  const polygonGraphic = new Graphic({
    geometry: polygon,
    symbol: simpleFillSymbol,
  });
  drawLayer.add(polygonGraphic);
};
